//
//  SQContentView.swift
//  SQPageView
//
//  Created by ToothBond on 2017/4/24.
//  Copyright © 2017年 rensq. All rights reserved.
//

import UIKit

protocol SQContentViewDelegate : class{
    func contentView(_ contentView : SQContentView, didEndScroll inIndex : Int)
    func contentView(_ contentView : SQContentView, sourceIndex : Int, targetIndex : Int, progress : CGFloat)
}

class SQContentView: UIView {

    weak var delegate : SQContentViewDelegate?
    fileprivate var childVCs : [UIViewController]
    fileprivate var parentVC : UIViewController
    fileprivate var startOffsetX : CGFloat = 0
    fileprivate var isForbidDelegate : Bool = false
    
    //懒加载  编译期间不会赋值，所以需要明确指定变量的类型
//    fileprivate lazy var collectionView : UICollectionView = UICollectionView(frame: self.bounds, collectionViewLayout: UICollectionViewFlowLayout())
    
    
    //闭包  执行闭包()  return闭包中的返回值
    fileprivate lazy var collectionView : UICollectionView = {
        
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = self.bounds.size
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
        
        let collectionView = UICollectionView(frame: self.bounds, collectionViewLayout: layout)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.isPagingEnabled = true
        collectionView.bounces = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "UICollectionViewCell")
        collectionView.scrollsToTop = false
        
        return collectionView
    }()
    
    init(frame: CGRect,childVCs : [UIViewController], parentVC : UIViewController) {
        self.childVCs = childVCs
        self.parentVC = parentVC
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")

    }

}

// MARK: - 设置UI界面
extension SQContentView{
    fileprivate func setupUI() {
        for childVC in childVCs {
            parentVC .addChildViewController(childVC)
        }
        
        addSubview(collectionView)
    }
}

extension SQContentView : UICollectionViewDataSource, UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return childVCs.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "UICollectionViewCell", for: indexPath)
        
        //添加内容
        for subView in cell.contentView.subviews{
            subView.removeFromSuperview()
        }
        let childVC = childVCs[indexPath.row]
        cell.contentView.addSubview(childVC.view)
        
        return cell
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        didEndScroll()
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if !decelerate {
            didEndScroll()
        }
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        startOffsetX = scrollView.contentOffset.x
        isForbidDelegate = false
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        if isForbidDelegate {return}
        if scrollView.contentOffset.x == startOffsetX {return}
        
        var sourceIndex = 0
        var targetIndex = 0
        var progress : CGFloat = 0
        
        let contentOffsetX = scrollView.contentOffset.x
        let collectionWidth = collectionView.bounds.width
        if contentOffsetX - startOffsetX > 0 { //  <--滑动方向
            sourceIndex = Int(contentOffsetX/collectionWidth)
            targetIndex = sourceIndex + 1
            if targetIndex >= childVCs.count {
                targetIndex = childVCs.count - 1
            }
            progress = (contentOffsetX - startOffsetX)/collectionWidth
            
            if contentOffsetX - startOffsetX == collectionWidth {
                targetIndex = sourceIndex
            }
            
        }else{  // --> 滑动方向
            targetIndex = Int(contentOffsetX/collectionWidth)
            sourceIndex = targetIndex + 1
            progress = (startOffsetX - contentOffsetX)/collectionWidth
        }
//        print("\(sourceIndex)   \(targetIndex)   \(progress)")
        delegate?.contentView(self, sourceIndex: sourceIndex, targetIndex: targetIndex, progress: progress)
    }
    
    private func didEndScroll() {
        let index = Int(collectionView.contentOffset.x/collectionView.bounds.width)
        delegate?.contentView(self, didEndScroll: index)
    }
}

extension SQContentView : SQTitleViewDelegate{
    func titleView(_ titleView: SQTitleView, targetIndex: Int) {
        
        isForbidDelegate = true
        
        let indexPath = IndexPath(item: targetIndex, section: 0)
        collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: false)
    }
    
    
}
